'use strict';
const db = uniCloud.database();
const comments = db.collection('opendb-news-comments');
const dbCmd = db.command
const $ = db.command.aggregate
exports.main = async (event, context) => {
	console.log('event : ', event)
	let {article_id,limit,secondLimit,page}=event
	// 过滤掉reply_comment_id不存在的数据（match过滤掉reply_comment_id不存在的数据），但后面的lookup是将_id==reply_comment_id数据筛选出放到
	// 指定的children中，符合条件，则children中有数据，不符合条件则没有；
	let res=await db.collection('opendb-news-comments').aggregate().match({
			article_id:article_id,
			// reply_comment_id:dbCmd.exists(false)
			comment_type:0, //针对文章
			isShow:false
		})
		.lookup({
			from: 'opendb-news-comments',
			// localField: '_id',
			// foreignField:'reply_comment_id',
			let: {id: '$_id'},
			pipeline: $.pipeline()
			.match(
				dbCmd.expr(
					$.eq(['$reply_comment_id','$$id'])
				)	
			)
			.match({
				isShow:false
			})
			.lookup({
				from: 'uni-id-users',
				let: {
				  uid: '$user_id'
				},
				pipeline: $.pipeline()
				  .match(
					dbCmd.expr($.eq(['$_id', '$$uid']))
				  )
				  .project({
					username:1,
					avatar:1,
					register_ip:1
				  })
				  .done(),
				as: 'userList'
			}) 
			.lookup({
			  	from: 'uni-id-users',
			  	let: {
			  	  reply_user_id: '$reply_user_id'
			  	},
			  	pipeline: $.pipeline()
			  	  .match(
			  		dbCmd.expr($.eq(['$_id', '$$reply_user_id']))
			  	  )
			  	  .project({
			  		username:1,
			  		avatar:1,
			  		register_ip:1
			  	  })
			  	  .done(),
			  	as: 'replycommentList'
			}) 
			.lookup({
			  	from: 'comments-like',
			  	let: {
			  	  ids: '$_id'
			  	},
			  	pipeline: $.pipeline()
			  	  .match(
			  		dbCmd.expr($.eq(['$comment_id','$$ids']))
			  	  )
			  	  .done(),
			  	as: 'commetLike'
			})
			.sort({
				comment_date: -1,
			})
			.limit(secondLimit)
			.done(),
			as: 'children'
		})
		.lookup({
			from: 'uni-id-users',
			let: {
			  uid: '$user_id'
			},
			pipeline: $.pipeline()
			  .match(
				dbCmd.expr($.eq(['$_id','$$uid']))
			  )
			  .project({
				username:1,
				avatar:1,
				register_ip:1
			  })
			  .done(),
			as: 'userList'
		})
		.lookup({
			from: 'comments-like',
			let: {
			  ids: '$_id'
			},
			pipeline: $.pipeline()
			  .match(
				dbCmd.expr($.eq(['$comment_id','$$ids']))
			  )
			  .done(),
			as: 'commetLike'
		})
		.sort({
			comment_date: -1,
		})
		.skip(page*limit)
		.limit(limit)
		.end()
	return res
};
